﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Security.Cryptography;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.RegularExpressions;
using CoreShop.App;
using CoreShop.Library;
using CoreShop.Services;
using System.Windows.Forms;
using CoreShop.Model;
using CoreShop.PrintService;
using SqlSugar;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.Rebar;
using Yitter.IdGenerator;
using SqlSugar.Extensions;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using Sunny.UI;
using System.Xml;
using NPOI.SS.Formula.Functions;
using NPOI.Util;
using CoreShop.Model.UI;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using static System.Windows.Forms.AxHost;
using Sunny.UI.Win32;
using IWshRuntimeLibrary;
using FastMember;
using PluSoft.Utils;
using System.Threading.Tasks;
using CoreShop.Model.FromBody;
using Org.BouncyCastle.Asn1.Tsp;
using CoreShop.App.Properties;
using System.Threading;
using static CoreShop.Services.PosRemoteServices;
using CoreShop.Library.Units;
using CoreShop.App.Units.Interface;

namespace CoreShop.App
{
    public class FoodUtil
    {

        /// <summary>
        /// 获取商品拍照图片名称
        /// </summary>
        /// <param name="food"></param>
        /// <returns></returns>
        public string GetProductLocaImageFile(corecmsfood food)
        {
            string fileNameByID = food.id.ToString() + ".jpg";
            string path = System.Windows.Forms.Application.StartupPath + "\\LocaleImg";
            string filename = path + "\\" + fileNameByID;
            return filename;
        }

        public void DownProductImage(List<corecmsfood> foodList)
        {
            try
            {
                if (!AppConstVars.systemsetup.showFoodImg) return;
                foreach (corecmsfood food in foodList)
                {
                    string imagePath = System.Windows.Forms.Application.StartupPath + "\\foodimg\\";
                    string rmoFileName = GetProductImageFile(food.image);//后台图片
                    if ((rmoFileName != null) && !System.IO.File.Exists(rmoFileName))
                    {
                        LogManager.WriteTxtLog($"下载图片:{rmoFileName}");
                        DownloadProductImage(food, rmoFileName);
                    }
                }
            }
            catch { }
        }

        /// <summary>
        /// 获取商品图片名称
        /// </summary>
        /// <param name="food"></param>
        /// <returns></returns>
        public string GetProductImageFile(string image)
        {
            if (string.IsNullOrEmpty(image)) return null;
            string imgPath = System.Windows.Forms.Application.StartupPath + "\\foodimg\\";
            string netImage = image.Replace("%","");
            int paraIndex = netImage.IndexOf("?");//去掉后面的参数
            if (paraIndex > 0)
            {
                netImage = netImage.Substring(0, paraIndex);
            }

            string filename = imgPath + System.IO.Path.GetFileName(netImage);
            return filename;
        }

        /// <summary>
        /// 下载商品图片
        /// </summary>
        public void DownloadProductImage(corecmsfood food,string path)
        {
            Task.Factory.StartNew(() =>
            {
                try
                {                    
                    //string path = System.Windows.Forms.Application.StartupPath + "\\foodimg\\"+ food.id.ToString();
                    ReturnModel returnModel = HttpHelper.DownloadFile(food.image);

                    if (returnModel.Status != ReturnStatus.Success || returnModel.DataOrEntityData.Empty())
                    {
                        return;
                    }

                    using (Stream stream = (Stream)returnModel.DataOrEntityData)
                    {
                        byte[] bytes = stream.StreamToByte();

                        using (FileStream fileStream = new FileStream(path, FileMode.Create))
                        {
                            fileStream.Write(bytes, 0, bytes.Length);
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogManager.WriteTxtLog($"下载图片失败:{ex.Message}");
                }
            }, TaskCreationOptions.LongRunning).TaskDis();
        }


        #region 根据商品ID生成ordering

        /// <summary>
        /// 根据商品类型ID查询类型名称
        /// </summary>
        /// <param name="custoType"></param>
        /// <returns></returns>
        public static decimal GetFoodWeigh(Form form, corecmsfoodordering ordering, ref decimal sQuantity)
        {
            var foodspec = new corecmsfoodspecServices().GetById(ordering.foodSpecId);
            if (foodspec == null) return sQuantity;
            
            frmFoodSpecWeigh foodSpecWeigh = new frmFoodSpecWeigh(ordering, foodspec, true);
            foodSpecWeigh.Owner = form;
            if (foodSpecWeigh.ShowDialog() == DialogResult.OK)
            {
                sQuantity = CommFunc.ConvertToDecimal(foodSpecWeigh.mScaleQty);
            }
            foodSpecWeigh.Dispose();
            return sQuantity;
        }

        #endregion
                
        #region 加载商品分类到Tree

        public void LoadFoodCategroy(UITreeView tvFood)
        {
            tvFood.Nodes.Clear();
            TreeNode treeNodeTop1 = new TreeNode("全部分类");
            treeNodeTop1.Tag = AppConstVars.sysStore.corpId;
            tvFood.Nodes.Add(treeNodeTop1);
            List<corecmsfoodcategory> lstSource = new corecmsfoodcategoryServices().AsQueryable().Where(p => p.isDelete != true && p.tenantId == AppConstVars.sysStore.corpId).ToList();
            var parents = lstSource.Where(p => p.parentId == 0).ToList();
            foreach (var item in parents)
            {
                TreeNode treeNode1 = new TreeNode(item.name);
                treeNode1.Tag = item.id.ToString();
                AddTreeNodeChilds(treeNode1, lstSource, item.id);
                treeNodeTop1.Nodes.Add(treeNode1);
            }

            //总店共享的分类
            List<corecmsfoodcategory> lstTenant = new corecmsfoodcategoryServices().QueryCorpFoodTypeId(AppConstVars.sysStore);
            if ((lstTenant != null) && (lstTenant.Count > 0))
            {
                corecmsfoodcategory foodcategory = lstTenant.First();
                TreeNode treeNodeTop2 = new TreeNode("总店共享");
                treeNodeTop2.Tag = foodcategory.tenantId;
                tvFood.Nodes.Add(treeNodeTop2);
                var parents2 = lstTenant.Where(p => p.parentId == 0).ToList();
                foreach (var item in parents2)
                {
                    TreeNode treeNode1 = new TreeNode(item.name);
                    treeNode1.Tag = item.id.ToString();
                    AddTreeNodeChilds(treeNode1, lstTenant, item.id);
                    treeNodeTop2.Nodes.Add(treeNode1);
                }
            }

            tvFood.Nodes[0].Expand();
        }

        public void AddTreeNodeChilds(TreeNode treeNode, List<corecmsfoodcategory> lstSource, long typeId)
        {
            var childs = lstSource.Where(p => p.parentId == typeId).ToList();
            if ((childs == null) || (childs.Count == 0)) return;

            foreach (var child in childs)
            {
                TreeNode treeNodeChild = new TreeNode(child.name);
                treeNodeChild.Tag = child.id.ToString();
                treeNode.Nodes.Add(treeNodeChild);
                AddTreeNodeChilds(treeNodeChild, lstSource, child.id);
            }
        }

        #endregion
    }
}
